#!/bin/sh
set -e

iptables="/sbin/iptables"
modprobe="/sbin/modprobe"

load () {
  echo "Loading kernel modules..."
  $modprobe ip_tables
  $modprobe ip_conntrack
  $modprobe iptable_filter
  $modprobe ipt_state
  echo "Kernel modules loaded."

  echo "Loading rules..."
  $iptables -P FORWARD DROP
  $iptables -P INPUT DROP

  $iptables -A INPUT -p tcp -m tcp --destination-port 22 -j ACCEPT
  $iptables -A INPUT -p ALL -m state --state ESTABLISHED,RELATED -j ACCEPT
  $iptables -A INPUT -s 127.0.0.1 -j ACCEPT
  echo "Rules loaded."
}

flush () {
  echo "Flushing rules..."
  $iptables -P FORWARD ACCEPT
  $iptables -F INPUT
  $iptables -P INPUT ACCEPT
  echo "Rules flushed."
}

case "$1" in
  start|restart)
    flush
    load
    ;;
  stop)
    flush
    ;;
  *)
    echo "usage: start|stop|restart."
    ;;
esac
exit 0